Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Collections.Generic
Imports InputControls
Imports Cdm.AppServices
Imports Cdm.DataCore
Imports Cdm.DataCore.Entities
Imports Cdm.DataCore.UserSecurity

Partial Class Search_AdvancedSearch
    Inherits System.Web.UI.Page

#Region "CONSTANTS"
    Private Const _CLASS_NAME As String = "Search_AdvancedSearch"
    Private Const _DEFAULT_DROPDOWNLIST_VALUE As String = "-1"
    Private Const _DEFAULT_DROPDOWNLIST_TEXT As String = ""
    Private Const _SESSION_HASHTABLE_NAME As String = "AdvancedSearchHashtable"
    Private Const _NEXT_PLAN_OF_CARE_SPECIFIER_TEXT As String = "@NextPlanOfCareSpecifier"
    Private Const _NEXT_PHONE_MONITORING_SPECIFIER_TEXT As String = "@NextPhoneMonitoringSpecifier"
    Private Const _NEXT_IN_HOME_MONITORING_SPECIFIER_TEXT As String = "@NextInHomeMonitoringSpecifier"
    Private Const _NEXT_ASSESSMENT_SPECIFIER_TEXT As String = "@NextAssessmentSpecifier"
#End Region

#Region "PRIVATE MEMBERS & ACCESSORS"

    Private _hashtable As Hashtable
    Private _parameterCount As Integer = 0
    Private _sortBy As String = String.Empty

#End Region

#Region "PUBLIC METHODS"

    Public Property SqlParameters() As Hashtable
        Get
            Return Me._hashtable
        End Get
        Set(ByVal value As Hashtable)
            Me._hashtable = value
        End Set
    End Property

    Public Property ParameterCount() As Integer
        Get
            Return Me._parameterCount
        End Get
        Set(ByVal value As Integer)
            Me._parameterCount = value
        End Set
    End Property

#End Region

#Region "PRIVATE METHODS"

    Protected Sub BindDropDowns()

        Try

            'COUNTY DROPDOWNLIST
            Me.CountyDropDownList.DataSource = LookupTables.LuCounty.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.CountyDropDownList.DataBind()

            'FILE STATUS DROPDOWNLIST
            Me.FileStatusDropDownList.DataSource = LookupTables.LuCaseStatus.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.FileStatusDropDownList.DataBind()

            'SPENDING PLAN STATUS DROPDOWNLIST
            Me.SpendingPlanStatusDropDownList.DataSource = LookupTables.LuSpendingPlanStatus.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.SpendingPlanStatusDropDownList.DataBind()

            'FMSA AGENCY DROPDOWNLIST
            Me.FMSAAgencyDropDownList.DataSource = Entities.FMSA.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.FMSAAgencyDropDownList.DataBind()

            'EMPLOYEE SERVICE TYPE
            Me.ServiceTypeDropDownList.DataSource = LookupTables.LuEmployeeServiceType.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.ServiceTypeDropDownList.DataBind()

            'SUPPORT BROKER AGENCY DROPDOWNLIST
            Me.SupportBrokerAgencyDropDownList.DataSource = Entities.SupportBrokerAgency.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.SupportBrokerAgencyDropDownList.DataBind()
            Me.SupportBrokerAgencyDropDownList.Items.Add(New ListItem("No Support Broker Agency", 0))

            'SUPPORT BROKER DROPDOWNLIST
            Me.PopulateSupportBrokers()

            'LOCAL PROGRAM OFFICE
            Me.LocalProgramOfficeDropDownList.Visible = True
            Me.LocalProgramOfficeDropDownList.DataSource = Entities.LocalProgram.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.LocalProgramOfficeDropDownList.DataBind()

            If LocalProgramOfficeDropDownList.Items.Count <= 1 Then
                Me.LocalProgramOfficeDropDownList.Visible = False
            Else
                Me.LocalProgramOfficeDropDownList.Visible = True
            End If

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in BindDropDowns() method.", ex)
            Throw ex
        End Try

    End Sub

    Protected Sub SetHashValue(ByVal control As IInputControl, ByVal key As String)

        Dim value As String = ""

        Try

            'STORE THE VALUE OF THE CONTROL LOCALLY
            value = control.Value

            If TypeOf control Is TextInputControl Or TypeOf control Is DateInputControl Or TypeOf control Is SSNInputControl Then

                If value.Trim().Length > 0 Then
                    Me._hashtable.Add(key, value.Trim())
                    Me._parameterCount = Me._parameterCount + 1
                Else
                    Me._hashtable.Add(key, System.DBNull.Value)
                End If

            ElseIf TypeOf control Is DropDownInputContol Then

                Try
                    If value <> _DEFAULT_DROPDOWNLIST_VALUE Then
                        Me._hashtable.Add(key, value.Trim())
                        Me._parameterCount = Me._parameterCount + 1
                    Else
                        Me._hashtable.Add(key, System.DBNull.Value)
                    End If
                Catch iex As InvalidCastException
                    Me._hashtable.Add(key, System.DBNull.Value)
                End Try

            End If

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in SetHashValue(IInputControl, String) method.", ex)
            Throw ex
        End Try

    End Sub

    Protected Sub SetHashValue(ByVal control As RadioButtonList, ByVal key As String)

        Try

            Me._hashtable.Add(key, control.SelectedValue)

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in SetHashValue(RadioButtonList, String) method.", ex)
            Throw ex
        End Try

    End Sub

    Protected Sub SetHashValue(ByVal control As IInputControl)

        Try

            Me.SetHashValue(control, control.BoundProperty)

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in SetHashValue(IInputControl) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PopulateSupportBrokers()

        Try

            Me.PopulateSupportBrokers(Me.SupportBrokerAgencyDropDownList.Value)

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PopulateSupportBrokers() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PopulateSupportBrokers(ByVal supportBrokerAgencyId As Integer)

        Try

            Me.SupportBrokerDropDownList.DataSource = Cdm.DataCore.Entities.SupportBroker.ListByAgency(supportBrokerAgencyId, _DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
            Me.SupportBrokerDropDownList.DataBind()

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PopulateSupportBrokers(Integer) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub SetFormPermissons()

        Try

            Dim userID As Integer = UserAuthorization.CurrentUser.UserId
            Dim roleId As Integer = UserAuthorization.CurrentUser.RoleId

            If roleId = Role.RoleType.FMSA Or _
                roleId = Role.RoleType.FMSAAdmin Then

                'GET THE FMSA OBJECT FOR THIS USER
                Dim oFmsaUser As FMSAUser
                oFmsaUser = Cdm.DataCore.Entities.FMSAUser.RetrieveByUserId(userID)

                'PRE-SELECT THE DROPDOWN VALUE & DISABLE THE DROPDOWN
                Me.FMSAAgencyDropDownList.Value = oFmsaUser.FMSAId
                Me.FMSAAgencyDropDownList.Editable = False

            ElseIf roleId = Role.RoleType.SupportBrokerAdmin Then

                Dim oSupportBrokerAdmin As SupportBroker = Nothing
                oSupportBrokerAdmin = Entities.SupportBroker.RetrieveByUserId(userID)
                Me.SupportBrokerAgencyDropDownList.Value = oSupportBrokerAdmin.SupportBrokerAgencyId

                'PRE-SELECT THE DROPDOWN VALUE & DISABLE THE DROPDOWN
                Me.PopulateSupportBrokers(oSupportBrokerAdmin.SupportBrokerAgencyId)
                Me.SupportBrokerAgencyDropDownList.Editable = False

            ElseIf roleId = Role.RoleType.SupportBroker Then

                Dim oSupportBroker As SupportBroker
                oSupportBroker = Entities.SupportBroker.RetrieveByUserId(userID)

                'PRE-SELECT THE DROPDOWN VALUE & DISABLE THE DROPDOWN
                Me.SupportBrokerAgencyDropDownList.Value = oSupportBroker.SupportBrokerAgencyId
                Me.SupportBrokerAgencyDropDownList.Editable = False
                Me.PopulateSupportBrokers(oSupportBroker.SupportBrokerAgencyId)

                Me.SupportBrokerDropDownList.Value = oSupportBroker.SupportBrokerId
                Me.SupportBrokerDropDownList.Editable = False

            ElseIf roleId = Role.RoleType.LocalProgramUser Then

                Dim oLocalProgramUser As LocalProgramUser
                oLocalProgramUser = Entities.LocalProgramUser.RetrieveByUserId(userID)

                Me.LocalProgramOfficeDropDownList.Value = oLocalProgramUser.LocalProgramId
                Me.LocalProgramOfficeDropDownList.Editable = False

            End If

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in SetFormPermissons() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PrePoupulateForm()

        Try

            Me.PrePopulateControl(Me.LastNameTextBox)
            Me.PrePopulateControl(Me.FirstNameTextBox)
            Me.PrePopulateControl(Me.SSNTextBox)
            Me.PrePopulateControl(Me.MedicaidNumberTextBox)
            Me.PrePopulateControl(Me.PrimaryLanguageTextBox)
            Me.PrePopulateControl(Me.SecondaryLanguageTextBox)
            Me.PrePopulateControl(Me.EmployeeLastNameTextBox)
            Me.PrePopulateControl(Me.EmployeeFirstNameTextBox)

            Me.PrePopulateControl(Me.CountyDropDownList)
            Me.PrePopulateControl(Me.FileStatusDropDownList)
            Me.PrePopulateControl(Me.SpendingPlanStatusDropDownList)
            Me.PrePopulateControl(Me.FMSAAgencyDropDownList)
            Me.PrePopulateControl(Me.ServiceTypeDropDownList)
            Me.PrePopulateControl(Me.LocalProgramOfficeDropDownList)
            Me.PrePopulateControl(Me.SupportBrokerAgencyDropDownList)
            Me.PopulateSupportBrokers()
            Me.PrePopulateControl(Me.SupportBrokerDropDownList)

            Me.PrePopulateControl(Me.BirthDate)
            Me.PrePopulateControl(Me.NextPlanOfCareDate)
            Me.PrePopulateControl(Me.NextInHomeMonitoringDate)
            Me.PrePopulateControl(Me.NextPhoneMonitoringDate)
            Me.PrePopulateControl(Me.NextAssessmentDate)

            Me.PrePopulateControl(Me.NextAssessmentDateRadioButtonList, _NEXT_ASSESSMENT_SPECIFIER_TEXT)
            Me.PrePopulateControl(Me.NextInHomeMonitoringRadioButtonList, _NEXT_IN_HOME_MONITORING_SPECIFIER_TEXT)
            Me.PrePopulateControl(Me.NextPhoneMonitoringRadioButtonList, _NEXT_PHONE_MONITORING_SPECIFIER_TEXT)
            Me.PrePopulateControl(Me.NextPlanOfCareRadioButtonList, _NEXT_PLAN_OF_CARE_SPECIFIER_TEXT)

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PopulateSearchFromSession() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PrePopulateControl(ByVal textBox As TextInputControl)

        Try

            Dim value As String = String.Empty

            If Not Me._hashtable(textBox.BoundProperty).Equals(DBNull.Value) Then
                value = CType(Me._hashtable.Item(textBox.BoundProperty), String)
            End If

            textBox.Value = value

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PrePopulateControl(TextInputControl) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PrePopulateControl(ByVal dropDownList As DropDownInputContol)

        Try

            Dim value As String = _DEFAULT_DROPDOWNLIST_VALUE.ToString()

            If Not Me._hashtable(dropDownList.BoundProperty).Equals(DBNull.Value) Then
                value = CType(Me._hashtable.Item(dropDownList.BoundProperty), String)
            End If

            dropDownList.Value = value

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PrePopulateControl(DropDownInputContol) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PrePopulateControl(ByVal dateControl As DateInputControl)

        Try

            Dim value As String = String.Empty

            If Not Me._hashtable(dateControl.BoundProperty).Equals(DBNull.Value) Then
                value = CType(Me._hashtable.Item(dateControl.BoundProperty), String)
            End If

            dateControl.Value = value

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PrePopulateControl(DateInputControl) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PrePopulateControl(ByVal radioList As RadioButtonList, ByVal radioName As String)

        Try

            If Me._hashtable.Item(radioName).Equals(DBNull.Value) Then
                radioList.SelectedValue = "Before"
            Else
                radioList.SelectedValue = Me._hashtable(radioName).ToString().Trim()
            End If

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PrePopulateControl(RadioButtonList, String) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PrePopulateControl(ByVal ssnControl As SSNInputControl)

        Try

            Dim value As String = String.Empty

            If Not Me._hashtable(ssnControl.BoundProperty).Equals(DBNull.Value) Then
                value = CType(Me._hashtable.Item(ssnControl.BoundProperty), String)
            End If

            ssnControl.Value = value

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error in PrePopulateControl(TextInputControl) method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub ResetForm()

        Try

            Me.LastNameTextBox.Value = String.Empty
            Me.FirstNameTextBox.Value = String.Empty
            Me.SSNTextBox.Value = String.Empty
            Me.MedicaidNumberTextBox.Value = String.Empty
            Me.PrimaryLanguageTextBox.Value = String.Empty
            Me.SecondaryLanguageTextBox.Value = String.Empty
            Me.EmployeeLastNameTextBox.Value = String.Empty
            Me.EmployeeFirstNameTextBox.Value = String.Empty

            Me.CountyDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.FileStatusDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.SpendingPlanStatusDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.ServiceTypeDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.FMSAAgencyDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.LocalProgramOfficeDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.SupportBrokerAgencyDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.SupportBrokerDropDownList.SelectedIndex = _DEFAULT_DROPDOWNLIST_VALUE
            Me.SetFormPermissons()

            Me.BirthDate.Value = DateTime.MinValue
            Me.NextPlanOfCareDate.Value = DateTime.MinValue
            Me.NextInHomeMonitoringDate.Value = DateTime.MinValue
            Me.NextPhoneMonitoringDate.Value = DateTime.MinValue
            Me.NextAssessmentDate.Value = DateTime.MinValue

            Me.NextAssessmentDateRadioButtonList.Items(1).Selected = True
            Me.NextInHomeMonitoringRadioButtonList.Items(1).Selected = True
            Me.NextPhoneMonitoringRadioButtonList.Items(1).Selected = True
            Me.NextPlanOfCareRadioButtonList.Items(1).Selected = True

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "Error in ResetForm() method.", ex)
            Throw ex
        End Try
    End Sub

    Private Function CreateSqlQuery() As String

        Dim sqlString As String = ""

        Try

            sqlString = "EXECUTE spSearchFiles "

            For Each parameter As DictionaryEntry In Me._hashtable
                If parameter.Key = "@SortBy" Then

                    Me._sortBy = parameter.Value.ToString()

                Else

                    If parameter.Value.Equals(System.DBNull.Value) Or parameter.Value.Equals(String.Empty) Then
                        sqlString = sqlString & parameter.Key & " = NULL, "
                    Else
                        sqlString = sqlString & parameter.Key & " = '" & parameter.Value & "', "
                    End If

                End If

            Next

            'REMOVE THE LAST COMMA
            sqlString = sqlString.Remove(sqlString.LastIndexOf(","), 1)

            'Response.Write("SQL String ==>" & sqlString & "<==")

            Return sqlString

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "An error occurred in GetSearchResults() method.", ex)
            Throw ex
        End Try

    End Function

    Private Sub DisplayData()

        Dim sqlString As String = ""
        Dim listAdvancedSearch As List(Of Cdm.DataCore.Custom.AdvancedSearch) = Nothing

        Try

            'GET THE SQL QUERY
            sqlString = Me.CreateSqlQuery()

            Me.QueryStringHiddenField.Value = sqlString

            listAdvancedSearch = Cdm.DataCore.Custom.AdvancedSearch.Search(sqlString, Me._sortBy)

            Me.SearchResultsScrollingGridView.DataSource = listAdvancedSearch
            Me.SearchResultsScrollingGridView.DataBind()

            Me.SearchResultsCountLabel.Text = "Files returned: " & listAdvancedSearch.Count

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "An error occurred in DisplayData() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub BindData()

        Try

            Me.SearchResultsScrollingGridView.DataSource = Cdm.DataCore.Custom.AdvancedSearch.Search(Me.QueryStringHiddenField.Value, Me.SortExpressionHiddenField.Value & " " & Me.SortDirectionHiddenField.Value)
            Me.SearchResultsScrollingGridView.DataBind()

            'Me.hfSubmitSearch.Value = "TRUE"

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the BindData() method.", ex)
            Throw ex
        End Try

    End Sub

#End Region

#Region "EVENT HANDLERS"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        Dim bLoadPage As Boolean = True

        SetupJavaScript()
        Form.DefaultButton = Me.SearchButton.UniqueID

        If Not Me.IsPostBack Then
            EntityController.SetPageDisplayNames(Me.Controls)
            bLoadPage = CheckPagePermission()
        Else
            Me.SSNTextBox.SetValueFromRequest()
        End If

        If bLoadPage Then
            Try


                Me.NextAssessmentDateRadioButtonList.Items(0).Attributes.Add("Title", "Next Assessment Date occurs on")
                Me.NextAssessmentDateRadioButtonList.Items(1).Attributes.Add("Title", "Next Assessment Date occurs before")
                Me.NextAssessmentDateRadioButtonList.Items(2).Attributes.Add("Title", "Next Assessment Date occurs after")

                Me.NextInHomeMonitoringRadioButtonList.Items(0).Attributes.Add("Title", "Next In-Home Monitoring Date occurs on")
                Me.NextInHomeMonitoringRadioButtonList.Items(1).Attributes.Add("Title", "Next In-Home Monitoring Date occurs before")
                Me.NextInHomeMonitoringRadioButtonList.Items(2).Attributes.Add("Title", "Next In-Home Monitoring Date occurs after")

                Me.NextPhoneMonitoringRadioButtonList.Items(0).Attributes.Add("Title", "Next Phone Monitoring Date occurs on")
                Me.NextPhoneMonitoringRadioButtonList.Items(1).Attributes.Add("Title", "Next Phone Monitoring Date occurs before")
                Me.NextPhoneMonitoringRadioButtonList.Items(2).Attributes.Add("Title", "Next Phone Monitoring Date occurs after")

                Me.NextPlanOfCareRadioButtonList.Items(0).Attributes.Add("Title", "Next Plan of Care Date occurs on")
                Me.NextPlanOfCareRadioButtonList.Items(1).Attributes.Add("Title", "Next Plan of Care Date occurs before")
                Me.NextPlanOfCareRadioButtonList.Items(2).Attributes.Add("Title", "Next Plan of Care Date occurs after")

                If Not Me.IsPostBack Then

                    'HIDE/DISPLAY LAST SEARCH LINK
                    If Session.Item(_SESSION_HASHTABLE_NAME) Is Nothing Then
                        Me.LastSearchLinkButton.Visible = False
                    Else
                        Me.LastSearchLinkButton.Visible = True
                    End If

                    If UserAuthorization.HasInsertPermission(Permission.PermissionType.CasePersonal) Then
                        Me.FileSubNavMenuDiv.Visible = True
                    Else
                        Me.FileSubNavMenuDiv.Visible = False
                    End If

                    'FILL THE FORM DROPDOWN LISTS
                    Me.BindDropDowns()

                    'SET FORM PERMISSIONS
                    Me.SetFormPermissons()

                    If Not Request("qs") Is Nothing Then
                        Me.LastNameTextBox.Value = Request("qs").ToString()
                        PerformSearch()
                    End If

                End If

            Catch ex As ApplicationException
                Log.ErrorLog(_CLASS_NAME, "Error occurred in Page_Load() method.", ex)
            End Try
        End If
    End Sub

    Private Sub SetupJavaScript()
        EntityController.JavaScriptAddChildDiv(Me.SearchCriteriaDiv.ClientID, 30)
        EntityController.JavaScriptAddChildDiv(Me.mainSearchPane.ClientID, 50)
        EntityController.JavaScriptAddChildDiv(Me.SearchResultsDiv.ClientID, 10)
        EntityController.JavaScriptAddChildDiv(Me.SearchResultsScrollingGridView.DivClientId, 100)
        EntityController.JavaScriptSetFixedHeight(30)
    End Sub

    Private Sub SetupJavaScript(ByVal isVisible As Boolean)
        If isVisible Then
            SetupJavaScript()
        Else
            EntityController.JavaScriptAddChildDiv(Me.mainSearchPane.ClientID, 50)
            EntityController.JavaScriptAddChildDiv(Me.SearchResultsDiv.ClientID, 10)
            EntityController.JavaScriptAddChildDiv(Me.SearchResultsScrollingGridView.DivClientId, 100)
            EntityController.JavaScriptSetFixedHeight(0)
        End If
    End Sub

    Private Function CheckPagePermission() As Boolean
        Dim hasPermission As Boolean = UserAuthorization.HasViewPermission(Permission.PermissionType.CasePersonal)
        If hasPermission = False Then
            Me.NoPermissionsDiv.Visible = True
            Me.mainSearchPane.Visible = False
            SetCommandButtonsVisible(False)
            Me.LastSearchLinkButton.Visible = False
        Else
            Me.NoPermissionsDiv.Visible = False
        End If

        Return hasPermission
    End Function

    Private Sub SetCommandButtonsVisible(ByVal isVisible As Boolean)
        Me.SearchButton.Visible = isVisible
        Me.ResetButton.Visible = isVisible
        SetupJavaScript(isVisible)
    End Sub

    Protected Sub SupportBrokerAgencyDropDownList_SelectedIndexChanged() Handles SupportBrokerAgencyDropDownList.SelectedIndexChanged

        Try

            Me.PopulateSupportBrokers()

        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error occurred in ddlFMSAAgency_SelectedIndexChanged()", ex)
        End Try

    End Sub

    Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchButton.Click
        PerformSearch()
    End Sub

    Private Sub PerformSearch()
        Try

            If Me.SSNTextBox.Value.Length > 0 Then
                If Not Me.SSNTextBox.Value.Length >= 9 Then
                    Me.lblMessage.Value = "Please specify a valid SSN."
                    Me.lblMessage.Visible = True
                    Exit Sub
                Else
                    Me.lblMessage.Value = ""
                End If
            End If

            'RELEASE THE OLD HASHTABLE
            If Not Me._hashtable Is Nothing Then
                Me._hashtable = Nothing
            End If

            'CREATE A NEW HASH TABLE
            Me._hashtable = New Hashtable

            Me._parameterCount = 0

            '*- BEGIN - FORM INPUTS -*'
            Me.SetHashValue(Me.LastNameTextBox)
            Me.SetHashValue(Me.FirstNameTextBox)
            Me.SetHashValue(Me.SSNTextBox)
            Me.SetHashValue(Me.MedicaidNumberTextBox)
            Me.SetHashValue(Me.CountyDropDownList)
            Me.SetHashValue(Me.BirthDate)
            Me.SetHashValue(Me.PrimaryLanguageTextBox)
            Me.SetHashValue(Me.SecondaryLanguageTextBox)
            Me.SetHashValue(Me.FileStatusDropDownList)
            Me.SetHashValue(Me.SpendingPlanStatusDropDownList)
            Me.SetHashValue(Me.FMSAAgencyDropDownList)
            Me.SetHashValue(Me.ServiceTypeDropDownList)
            Me.SetHashValue(Me.SupportBrokerAgencyDropDownList)
            Me.SetHashValue(Me.SupportBrokerDropDownList)
            Me.SetHashValue(Me.EmployeeLastNameTextBox)
            Me.SetHashValue(Me.EmployeeFirstNameTextBox)
            Me.SetHashValue(Me.NextPlanOfCareDate)
            Me.SetHashValue(Me.NextInHomeMonitoringDate)
            Me.SetHashValue(Me.NextPhoneMonitoringDate)
            Me.SetHashValue(Me.NextAssessmentDate)
            Me.SetHashValue(Me.NextPlanOfCareRadioButtonList, _NEXT_PLAN_OF_CARE_SPECIFIER_TEXT)
            Me.SetHashValue(Me.NextPhoneMonitoringRadioButtonList, _NEXT_PHONE_MONITORING_SPECIFIER_TEXT)
            Me.SetHashValue(Me.NextInHomeMonitoringRadioButtonList, _NEXT_IN_HOME_MONITORING_SPECIFIER_TEXT)
            Me.SetHashValue(Me.NextAssessmentDateRadioButtonList, _NEXT_ASSESSMENT_SPECIFIER_TEXT)
            Me.SetHashValue(Me.LocalProgramOfficeDropDownList)
            Me._hashtable.Add("@SortBy", "LastName ASC, FirstName ASC")

            If Me._parameterCount <= 0 Then
                Me.lblMessage.Value = "Please specify search criteria."
                Me.lblMessage.Visible = True
                Exit Sub
            Else
                Me.lblMessage.Value = ""
            End If

            'STORE THE HASHTABLE INTO THE SESSION FOR PRE-POPULATION 
            Session.Add(_SESSION_HASHTABLE_NAME, Me._hashtable)

            Dim sqlString As String = Me.CreateSqlQuery()
            Me.DisplayData()

            Me.SearchCriteriaDiv.Visible = False
            SetCommandButtonsVisible(False)
            Me.SearchResultsDiv.Visible = True

        Catch iexc As InvalidCastException
            Response.Write("Invalid Cast occurred.")
        Catch ex As ApplicationException
            Log.ErrorLog(_CLASS_NAME, "Error occurred in btnSearch_Click() method.", ex)
        End Try

    End Sub

    Protected Sub LastSearchLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LastSearchLinkButton.Click

        Try

            'PREOPULATE THE FORM WITH LAST SEARCH CRITERIA
            If Not Session.Item(_SESSION_HASHTABLE_NAME) Is Nothing Then

                Me._hashtable = CType(Session.Item(_SESSION_HASHTABLE_NAME), Hashtable)
                Me.PrePoupulateForm()

            End If

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "Error occurred in LastSearchLinkButton_Click() method.", ex)
        End Try

    End Sub

    Protected Sub ResetButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ResetButton.Click
        Try

            Me.ResetForm()

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "Error occurred in ResetButton_Click() method.", ex)
        End Try
    End Sub

#End Region

    Protected Sub SearchResultsScrollingGridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles SearchResultsScrollingGridView.Sorting
        Try

            If Me.SortExpressionHiddenField.Value = e.SortExpression Then

                If Me.SortDirectionHiddenField.Value = "ASC" Or Me.SortDirectionHiddenField.Value = "" Then
                    Me.SortDirectionHiddenField.Value = "DESC"
                Else
                    Me.SortDirectionHiddenField.Value = "ASC"
                End If

            Else

                Me.SortExpressionHiddenField.Value = e.SortExpression
                Me.SortDirectionHiddenField.Value = "ASC"

            End If

            Me.BindData()

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SearchResultsScrollingGridView_Sorting() method.", ex)
        End Try
    End Sub
End Class
